<template>
  <div class="app-container">
    <el-tabs v-model="activeTab" type="card" @tab-click="handleTabClick">
      <el-tab-pane label="TCP模式" name="TCP">
        <!-- TCP模式的搜索区域 -->
        <el-form
          v-show="showSearch"
          ref="queryForm"
          :inline="true"
          :model="queryParams"
          label-width="68px"
        >
          <el-form-item label="IP地址" prop="ipAddress">
            <el-input
              v-model="queryParams.ipAddress"
              clearable
              placeholder="请输入IP地址"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="运行状态" prop="state">
            <el-select
              v-model="queryParams.state"
              clearable
              placeholder="请选择运行状态"
              style="width: 240px"
            >
              <el-option
                v-for="dict in dict.type.iot_state"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery"
            >搜索
            </el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button icon="el-icon-plus" plain size="mini" type="primary" @click="handleAdd"
            >新增
            </el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              :disabled="multiple"
              icon="el-icon-delete"
              plain
              size="mini"
              type="danger"
              @click="handleDelete"
            >删除
            </el-button
            >
          </el-col>
        </el-row>
        <!-- TCP模式的表格区域 -->
        <el-table
          v-loading="loading"
          :data="tcpMasterList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column align="center" type="selection" width="55"/>
          <el-table-column align="center" label="采集产品" prop="productName"/>
          <el-table-column align="center" label="IP地址" prop="ipAddress"/>
          <el-table-column align="center" label="端口" prop="port"/>
          <el-table-column align="center" label="采集频率（分钟）" prop="acquisitionFrequency"/>
          <el-table-column align="center" label="间隔时间(毫秒)" prop="intervalTime"/>
          <el-table-column align="center" label="运行状态" prop="state">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.state"
                :active-value="'1'"
                :inactive-value="'0'"
                @change="handleStateChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
            <template slot-scope="scope">
              <el-button
                icon="el-icon-edit"
                size="mini"
                type="text"
                @click="handleUpdate(scope.row)"
              >修改
              </el-button
              >
              <el-button
                icon="el-icon-delete"
                size="mini"
                type="text"
                @click="handleDelete(scope.row)"
              >删除
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <el-tab-pane label="RTU模式" name="RTU">
        <!-- RTU模式的搜索区域 -->
        <el-form
          v-show="showSearch"
          ref="queryForm"
          :inline="true"
          :model="queryParams"
          label-width="68px"
        >
          <el-form-item label="串口" prop="serialPort">
            <el-input
              v-model="queryParams.serialPort"
              clearable
              placeholder="请输入串口"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="运行状态" prop="state">
            <el-select
              v-model="queryParams.state"
              clearable
              placeholder="请选择运行状态"
              style="width: 240px"
            >
              <el-option
                v-for="dict in dict.type.iot_state"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery"
            >搜索
            </el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button icon="el-icon-plus" plain size="mini" type="primary" @click="handleAdd"
            >新增
            </el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              :disabled="multiple"
              icon="el-icon-delete"
              plain
              size="mini"
              type="danger"
              @click="handleDelete"
            >删除
            </el-button
            >
          </el-col>
        </el-row>
        <!-- RTU模式的表格区域 -->
        <el-table
          v-loading="loading"
          :data="rtuMasterList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column align="center" type="selection" width="55"/>
          <el-table-column align="center" label="采集产品" prop="productName"/>
          <el-table-column align="center" label="串口" prop="serialPort"/>
          <el-table-column align="center" label="波特率" prop="baudRate"/>
          <el-table-column align="center" label="数据位" prop="dataBits"/>
          <el-table-column align="center" label="校验位" prop="checkBit">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.iot_checkpoint_type" :value="scope.row.checkBit"/>
            </template>
          </el-table-column>
          <el-table-column align="center" label="停止位" prop="stopBit"/>
          <el-table-column align="center" label="采集频率（分钟）" prop="acquisitionFrequency"/>
          <el-table-column align="center" label="间隔时间(毫秒)" prop="intervalTime"/>
          <el-table-column align="center" label="运行状态" prop="state">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.state"
                :active-value="'1'"
                :inactive-value="'0'"
                @change="handleStateChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
            <template slot-scope="scope">
              <el-button
                icon="el-icon-edit"
                size="mini"
                type="text"
                @click="handleUpdate(scope.row)"
              >修改
              </el-button
              >
              <el-button
                icon="el-icon-delete"
                size="mini"
                type="text"
                @click="handleDelete(scope.row)"
              >删除
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <pagination
      v-show="total > 0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改采集器对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属产品" prop="productId">
          <el-select v-model="form.productId" placeholder="请选择所属产品">
            <el-option
              v-for="item in productOptions"
              :key="item.productId"
              :label="item.productName"
              :value="item.productId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="传输模式" prop="modeType">
          <el-select v-model="form.modeType" placeholder="请选择传输模式">
            <el-option
              v-for="dict in dict.type.iot_transfer_mode"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="form.modeType === 'RTU'" label="串口" prop="serialPort">
          <el-input v-model="form.serialPort" placeholder="请输入串口"/>
        </el-form-item>
        <el-form-item v-if="form.modeType === 'RTU'" label="波特率" prop="baudRate">
          <el-input v-model="form.baudRate" placeholder="请输入波特率"/>
        </el-form-item>
        <el-form-item v-if="form.modeType === 'RTU'" label="数据位" prop="dataBits">
          <el-input v-model="form.dataBits" placeholder="请输入数据位"/>
        </el-form-item>
        <el-form-item v-if="form.modeType === 'RTU'" label="校验位" prop="checkBit">
          <el-select v-model="form.checkBit" placeholder="请选择校验位">
            <el-option
              v-for="dict in dict.type.iot_checkpoint_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.modeType === 'RTU'" label="停止位" prop="stopBit">
          <el-input v-model="form.stopBit" placeholder="请输入停止位"/>
        </el-form-item>
        <el-form-item label="采集频率(分钟)" prop="acquisitionFrequency">
          <el-input v-model="form.acquisitionFrequency" placeholder="请输入间隔时间(分钟)"/>
        </el-form-item>
        <el-form-item label="间隔时间(毫秒)" prop="intervalTime">
          <el-input v-model="form.intervalTime" placeholder="请输入间隔时间(毫秒)"/>
        </el-form-item>
        <el-form-item v-if="form.modeType === 'TCP'" label="IP地址" prop="ipAddress">
          <el-input v-model="form.ipAddress" placeholder="请输入IP地址"/>
        </el-form-item>
        <el-form-item v-if="form.modeType === 'TCP'" label="端口" prop="port">
          <el-input v-model="form.port" placeholder="请输入端口号"/>
        </el-form-item>
        <el-form-item label="运行状态" prop="state">
          <el-select v-model="form.state" placeholder="请选择运行状态">
            <el-option
              v-for="dict in dict.type.iot_state"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addMasterConfig,
  delMasterConfig,
  getMasterConfig,
  listMasterConfig,
  updateMasterConfig
} from "@/api/system/iot/master";
import {findProductConfigList} from "@/api/system/iot/product";

export default {
  name: "MasterConfig",
  dicts: ["iot_transfer_mode", "iot_state", "iot_checkpoint_type"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采集器表格数据
      masterList: [],
      // 当前激活的标签页
      activeTab: "TCP",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        modeType: undefined,
        ipAddress: undefined,
        serialPort: undefined,
        state: undefined
      },
      // 表单参数
      form: {},
      productOptions: [],
      // 表单校验
      rules: {
        modeType: [{required: true, message: "传输模式不能为空", trigger: "change"}],
        serialPort: [{required: true, message: "串口不能为空", trigger: "blur"}],
        baudRate: [{required: true, message: "波特率不能为空", trigger: "blur"}],
        dataBits: [{required: true, message: "数据位不能为空", trigger: "blur"}],
        checkBit: [{required: true, message: "校验位不能为空", trigger: "change"}],
        stopBit: [{required: true, message: "停止位不能为空", trigger: "blur"}],
        intervalTime: [{required: true, message: "间隔时间不能为空", trigger: "blur"}],
        state: [{required: true, message: "运行状态不能为空", trigger: "change"}]
      }
    };
  },
  computed: {
    // TCP模式的采集器列表
    tcpMasterList() {
      return this.masterList.filter(item => item.modeType === "TCP");
    },
    // RTU模式的采集器列表
    rtuMasterList() {
      return this.masterList.filter(item => item.modeType === "RTU");
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 标签页切换事件 */
    handleTabClick() {
      this.getList();
    },
    /** 查询采集器列表 */
    getList() {
      this.loading = true;
      this.queryParams.modeType = this.activeTab;
      listMasterConfig(this.queryParams).then(response => {
        this.masterList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询产品选项 */
    getProductOptions() {
      findProductConfigList().then(response => {
        this.productOptions = response.data;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        modeType: this.activeTab,
        ipAddress: undefined,
        port: undefined,
        serialPort: undefined,
        baudRate: undefined,
        dataBits: undefined,
        checkBit: undefined,
        stopBit: undefined,
        intervalTime: undefined,
        acquisitionFrequency: undefined,
        state: "0",
        productId: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采集器";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getProductOptions();
      const id = row.masterId;
      getMasterConfig(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采集器";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.masterId != null) {
            updateMasterConfig(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMasterConfig(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除采集器编号为"' + ids + '"的数据项？')
        .then(function () {
          return delMasterConfig(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/master/export",
        {
          ...this.queryParams
        },
        `master_${new Date().getTime()}.xlsx`
      );
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.multiple = !selection.length;
    },
    /** 处理运行状态切换 */
    handleStateChange(row) {
      updateMasterConfig(row).then(response => {
        this.$modal.msgSuccess("状态更新成功");
        this.getList();
      }).catch(() => {
        row.state = row.state === '1' ? '0' : '1';
      });
    }
  }
};
</script>
